package com.howard.service.impl;

import java.lang.reflect.InvocationTargetException;
import java.util.Date;
import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataAccessException;
import org.springframework.dao.EmptyResultDataAccessException;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.howard.constants.EntityStatus;
import com.howard.dao.UserDao;
import com.howard.entity.User;
import com.howard.exception.ServiceException;
import com.howard.service.UserService;

@Service
@Transactional
public class UserServiceImpl implements UserService {

	private static final Logger LOGGER = LoggerFactory
			.getLogger(UserServiceImpl.class);

	private UserDao userDao;

	@Autowired
	public void setUserDao(UserDao userDao) {
		this.userDao = userDao;
	}

	@Transactional(readOnly = true)
	@Override
	public List<User> searchUserForList() throws ServiceException {
		try {
			return userDao.queryUserForList();
		} catch (DataAccessException dae) {
			LOGGER.error("query user error", dae);
			throw new ServiceException("query user error", dae);
		}
	}

	@Transactional(readOnly = true)
	@Override
	public User searchUserById(long id) throws ServiceException {
		try {
			return userDao.queryUserById(id);
		} catch (DataAccessException dae) {
			if(dae instanceof EmptyResultDataAccessException) {
				return null;
			}
			LOGGER.error("query user error", dae);
			throw new ServiceException("query user error", dae);
		}
	}

	@Override
	public User searchUserByAccName(String accountName) throws ServiceException {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public int[] addBatchUsers(List<User> user) throws ServiceException {
		// TODO Auto-generated method stub
		return null;
	}

	
	@Transactional(rollbackFor = ServiceException.class)
	@Override
	public long addUser(User user) throws ServiceException {
		if(user == null) {
			throw new IllegalArgumentException("argument [user] can not null");
		}
		user.setStatus(EntityStatus.ACTIVATION.getValue());
		user.setCreateDate(new Date());
		try {
			return userDao.insertUser(user);
		} catch (DataAccessException e) {
			throw new ServiceException("add user failed", e);
		} catch (IllegalAccessException e) {
			throw new ServiceException("add user failed", e);
		} catch (InvocationTargetException e) {
			throw new ServiceException("add user failed", e);
		} catch (NoSuchMethodException e) {
			throw new ServiceException("add user failed", e);
		}
	}

	@Override
	public void delUser(Long userId) throws ServiceException {
		try {
			userDao.deleteUser(userId);
		} catch (DataAccessException e) {
			throw new ServiceException("delete user faild", e);
		}

	}

}
